package com.fxsh168.server.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.baidu.trace.OnEntityListener;
import com.baidu.trace.OnStartTraceListener;
import com.baidu.trace.OnStopTraceListener;
import com.baidu.trace.OnTrackListener;
import com.baidu.trace.TraceLocation;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.maps.yinyan.DateUtils;
import com.fxsh168.server.maps.yinyan.MonitorService;
import com.fxsh168.server.maps.yinyan.TrackReceiver;
import com.fxsh168.server.otherviews.banner.MyApplication;
import com.fxsh168.server.utils.DecimalUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class QueryDistanceService extends Service {
    String ids;  //订单id，距离，导航标识
    String mDistance = "0";//距离初始化为0
    int lastDistance;//上一次的距离
    int backDistace;//往回走的距离
    //    以下是轨迹查询的-----------------------------------------
    protected static OnTrackListener trackListener = null;   //* Track监听器
    private int startTime = 0;
    private int endTime = 0;
    TrackUploadHandler mHandler = null;
    boolean isTraceStarted = false;
    private MyApplication trackApp = null;
    private int nowDistance;//现在的距离
    private int distance;//百度返回距离

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static String timeStampToDate(long timeStamp) {
        Date date = new Date(timeStamp);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }

    public static int getYearByTimeStamp(long timeStamp) {
        String date = timeStampToDate(timeStamp);
        String year = date.substring(0, 4);
        return Integer.parseInt(year);
    }

    public static int getMonthByTimeStamp(long timeStamp) {
        String date = timeStampToDate(timeStamp);
        String month = date.substring(5, 7);
        return Integer.parseInt(month);
    }

    public static int getDayByTimeStamp(long timeStamp) {
        String date = timeStampToDate(timeStamp);
        String day = date.substring(8, 10);
        return Integer.parseInt(day);
    }

    public static int getHourByTimeStamp(long timeStamp) {
        String date = timeStampToDate(timeStamp);
        String hour = date.substring(11, 13);
        return Integer.parseInt(hour);
    }

    public static int getMinuteByTimeStamp(long timeStamp) {
        String date = timeStampToDate(timeStamp);
        String minute = date.substring(14, 16);
        return Integer.parseInt(minute);
    }

    public static int getSecondByTimeStamp(long timeStamp) {
        String date = timeStampToDate(timeStamp);
        String second = date.substring(17, 19);
        return Integer.parseInt(second);
    }

    //    逻辑实现-------------------------------------------------------
//    获取年月日的方法
    public int gettime() {
        long times = System.currentTimeMillis();
        int year = getYearByTimeStamp(times);
        int intMon = getMonthByTimeStamp(times);
        int intDay = getDayByTimeStamp(times);
        int hours = getHourByTimeStamp(times);
        int minutes = getMinuteByTimeStamp(times);
        int miao = getSecondByTimeStamp(times);
        String st = year + "年" + intMon + "月" + intDay + "日" + hours + "时" + minutes + "分" + miao + "秒";
        int Times = Integer.parseInt(DateUtils.getTimeToStamp(st));
        Log.e("tag", "时间打印" + st);
        return Times;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        aboutYing();
        //   轨迹查询----------------------------------------------------
        startTime = gettime();    //起始时间
        initOnTrackListener();   //  初始化OnTrackListener
        mHandler = new TrackUploadHandler();
        getHandlerDistance.sendEmptyMessage(0);   // 发送请求获取距离
        //每次启动app都会执行这个方法，判断有没有数据，没有的话就表示没有发车，有数据说明已经接客，在提交订单的时候会设置为0
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        ids = intent.getStringExtra("ids");
    }

    private Handler getHandlerDistance = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            queryDistance(1, "need_denoise=1,need_vacuate=1,need_mapmatch=1");//纠偏后的距离
            getHandlerDistance.sendEmptyMessageDelayed(0, 5000);    //10秒获取一次距离
        }
    };

    // 查询里程
    private void queryDistance(int processed, String processOption) {
        SharedPreferences sp = getSharedPreferences(Constant.LOGINCLASS, MODE_PRIVATE);
        String entityName = sp.getString("mPhone", "");
        ;    // entity标识
        int isProcessed = processed;    // 是否返回纠偏后轨迹（0 : 否，1 : 是）
        String supplementMode = "driving";    // 里程补充
        endTime = gettime();   //获取当前结束时间
        Log.e("tag", "开始时间" + startTime + "结束时间" + endTime);
        trackApp.getClient().queryDistance(trackApp.getServiceId(), entityName, isProcessed, processOption,
                supplementMode, startTime, endTime, trackListener);
    }

    //     * 初始化OnTrackListener
    private void initOnTrackListener() {
        trackListener = new OnTrackListener() {
            // 请求失败回调接口
            @Override
            public void onRequestFailedCallback(String arg0) {
                Log.e("==================>", "轨迹回调接口失败" + arg0);
//                trackApp.getmHandler().obtainMessage(0, "track请求失败回调接口消息 : " + arg0).sendToTarget();
            }

            // 查询历史轨迹回调接口
            @Override
            public void onQueryHistoryTrackCallback(String arg0) {
                super.onQueryHistoryTrackCallback(arg0);
//                showHistoryTrack(arg0);   // 显示历史轨迹
            }

            @Override
            public void onQueryDistanceCallback(String arg0) {
                try {
                    JSONObject dataJson = new JSONObject(arg0);
                    if (null != dataJson && dataJson.has("status") && dataJson.getInt("status") == 0) {
                         distance = (int) dataJson.getDouble("distance");
//                        if (lastDistance < 0){
                            nowDistance = Integer.parseInt(getSharedPreferences("palced", Context.MODE_PRIVATE).getString("mDistance","0"));
//                            Log.e("===========>",lastDistance + "===========>" + nowDistance + "===========>" + backDistace + "==========>" + distance);
//                            nowDistance += Math.abs(lastDistance - distance);//上次减去这次的距离
//                        }else{
                            backDistace = Math.abs(lastDistance - distance);//上次减去这次的距离
                            nowDistance += backDistace;
                            Log.e("------------>",lastDistance + "------------>" + nowDistance + "------------>" + backDistace + "------------>" + distance);
//                        }
                        lastDistance = distance;//把上次的距离变成这次的
                        Log.e("-----",lastDistance + "----" + nowDistance + "----" + backDistace + "----" + distance);
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable(){
                            public void run(){
                                Toast.makeText(getApplicationContext(),"百度返回距离：" + distance + "\n" +  "上次距离：" + lastDistance + "\n" + "这次距离：" +nowDistance + "\n" + "两次距离差：" + backDistace, Toast.LENGTH_LONG).show();
                            }
                        });

                        /*DecimalFormat df = new DecimalFormat("#.0");
                        String format = df.format(distance);
                        distance = Double.parseDouble(format);*/
                        mDistance = String.valueOf(nowDistance);//下次的距离
                        Log.e("tag", ids + "像素"  +  "米" + mDistance + "原始" + distance);
//                        trackApp.getmHandler().obtainMessage(0, "里程 : " + df.format(distance) + "米").sendToTarget();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                sendDistance(mDistance);    //发送距离到服务器
                            }
                        }).start();
                    }
                } catch (JSONException e) {
//                    trackApp.getmHandler().obtainMessage(0, "queryDistance回调消息 : " + arg0).sendToTarget();
                }
            }

            @Override
            public Map<String, String> onTrackAttrCallback() {
                System.out.println("onTrackAttrCallback");
                return null;
            }
        };
    }

    //    发送距离
    public void sendDistance(String mDistance) {
        SharedPreferences mSharedPreferences = getSharedPreferences("palced", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString("mDistance", mDistance);
        editor.putBoolean("finish",false);
        editor.commit();
        Log.e("tag", "发送执行" + ids + "距离" + mDistance);
        OkHttpUtils.post()
                .addParams("id", ids)
                .addParams("distance", mDistance + "")
//                .addParams("time",System.currentTimeMillis() + "")
                .url(Constant.DRIVERSENDDISTANCE)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("tag", "发送距离错误输出" + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("tag", "司机实时距离发送" + response);
            }
        });
    }

    class TrackUploadHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                case 10006:
                case 10008:
                case 10009:
                    isTraceStarted = true;
                    Log.e("tag", "轨迹服务开启成功");
                    break;
                case 1:
                case 10004:
                    isTraceStarted = false;
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        /*SharedPreferences mSharedPreferences = getSharedPreferences("palced", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString("mDistance", mDistance);
        editor.commit();
        Log.e("tag", "服务里面的距离保存" + mDistance);*/
        super.onDestroy();
        trackApp.getClient().onDestroy();
        getHandlerDistance.removeMessages(0);
    }


    //   关于鹰眼服务的全部初始化
    public void aboutYing() {
        //       关于鹰眼服务的---------------------------------------------------
        init();           // 初始化
        initListener();     // 初始化监听器
        setInterval();      // 设置采集周期
        setRequestType();    // 设置http请求协议类型

    }

    //    * 设置采集周期和打包周期
    private void setInterval() {
        trackApp.getClient().setInterval(gatherInterval, packInterval);
    }


    //     * 设置请求协议
    protected void setRequestType() {
        int type = 0;
        trackApp.getClient().setProtocolType(type);
    }

    //    ----------------------------------鹰眼轨迹----------------------------------
    protected static OnStartTraceListener startTraceListener = null; //   * 开启轨迹服务监听器
    protected static OnStopTraceListener stopTraceListener = null;   //     * 停止轨迹服务监听器
    protected RefreshThread refreshThread = null;      //  * 刷新地图线程(获取实时点)
    private int packInterval = 15;   // * 打包周期（单位 : 秒）
    private static OnEntityListener entityListener = null;      //  * Entity监听器
    private int gatherInterval = 5;  //     * 采集周期（单位 : 秒）
    private Intent serviceIntent = null;
    private static boolean isRegister = false;
    protected static PowerManager pm = null;
    private TrackReceiver trackReceiver = new TrackReceiver();
    public static PowerManager.WakeLock wakeLock = null;

    public void init() {
        Toast.makeText(this, "正在开启轨迹服务，请稍候", Toast.LENGTH_SHORT).show();
        startTrace();
        if (!isRegister) {
            if (null == pm) {
                pm = (PowerManager) trackApp.getSystemService(Context.POWER_SERVICE);
            }
            if (null == wakeLock) {
                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload");
            }
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction("com.baidu.trace.action.GPS_STATUS");
            trackApp.registerReceiver(trackReceiver, filter);
            isRegister = true;
        }
    }
//     * 初始化监听器

    private void initListener() {
        // 初始化开启轨迹服务监听器
        if (null == startTraceListener) {
            initOnStartTraceListener();
        }

        // 初始化停止轨迹服务监听器
        if (null == stopTraceListener) {
            initOnStopTraceListener();
        }

        // 初始化entity监听器
        if (null == entityListener) {
            initOnEntityListener();
        }
    }

    /**
     * 初始化OnStartTraceListener
     */
    private void initOnStartTraceListener() {
        // 初始化startTraceListener
        startTraceListener = new OnStartTraceListener() {
            // 开启轨迹服务回调接口（arg0 : 消息编码，arg1 : 消息内容，详情查看类参考）
            public void onTraceCallback(int arg0, String arg1) {
//                mHandler.obtainMessage(arg0, "开启轨迹服务回调接口消息 [消息编码 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
            }

            // 轨迹服务推送接口（用于接收服务端推送消息，arg0 : 消息类型，arg1 : 消息内容，详情查看类参考）
            public void onTracePushCallback(byte arg0, String arg1) {
                if (0x03 == arg0 || 0x04 == arg0) {
                    try {
                        JSONObject dataJson = new JSONObject(arg1);
                        if (null != dataJson) {
                            String mPerson = dataJson.getString("monitored_person");
                            String action = dataJson.getInt("action") == 1 ? "进入" : "离开";
                            String date = DateUtils.getDate(dataJson.getInt("time"));
                            long fenceId = dataJson.getLong("fence_id");
//                            mHandler.obtainMessage(-1, "监控对象[" + mPerson + "]于" + date + " [" + action + "][" + fenceId + "号]围栏").sendToTarget();
                        }

                    } catch (JSONException e) {
//                        mHandler.obtainMessage(-1, "轨迹服务推送接口消息 [消息类型 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                    }
                } else {
//                    mHandler.obtainMessage(-1, "轨迹服务推送接口消息 [消息类型 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                }
            }

        };
    }

    /**
     * 初始化OnStopTraceListener
     */
    private void initOnStopTraceListener() {
        // 初始化stopTraceListener
        stopTraceListener = new OnStopTraceListener() {
            // 轨迹服务停止成功
            public void onStopTraceSuccess() {
//                mHandler.obtainMessage(1, "停止轨迹服务成功").sendToTarget();
                startRefreshThread(false);
                trackApp.getClient().onDestroy();
            }

            // 轨迹服务停止失败（arg0 : 错误编码，arg1 : 消息内容，详情查看类参考）
            public void onStopTraceFailed(int arg0, String arg1) {
//                mHandler.obtainMessage(-1, "停止轨迹服务接口消息 [错误编码 : " + arg0 + "，消息内容 : " + arg1 + "]").sendToTarget();
                startRefreshThread(false);
            }
        };
    }

    protected void startRefreshThread(boolean isStart) {
        if (null == refreshThread) {
            refreshThread = new RefreshThread();
        }
        refreshThread.refresh = isStart;
        if (isStart) {
            if (!refreshThread.isAlive()) {
                refreshThread.start();
            }
        } else {
            refreshThread = null;
        }
    }


    protected class RefreshThread extends Thread {
        protected boolean refresh = true;

        @Override
        public void run() {
            Looper.prepare();
            while (refresh) {
                // 轨迹服务开启成功后，调用queryEntityList()查询最新轨迹；
                // 未开启轨迹服务时，调用queryRealtimeLoc()进行实时定位。
//                queryRealtimeLoc();
                if (isTraceStarted) {
//                    queryEntityList();
                } else {
                    aboutYing();
                    queryRealtimeLoc();
                }
                try {
                    Thread.sleep(gatherInterval * 1000);
                } catch (InterruptedException e) {
                    System.out.println("线程休眠失败");
                }
            }
            Looper.loop();
        }
    }

//     * 查询实时轨迹

    private void queryRealtimeLoc() {
        trackApp.getClient().queryRealtimeLoc(trackApp.getServiceId(), entityListener);
    }


    /**
     * 初始化OnEntityListener
     */
    private void initOnEntityListener() {
        entityListener = new OnEntityListener() {
            // 请求失败回调接口
            @Override
            public void onRequestFailedCallback(String arg0) {
//                trackApp.getmHandler().obtainMessage(0, "entity请求失败回调接口消息 : " + arg0).sendToTarget();
            }

            // 添加entity回调接口
            public void onAddEntityCallback(String arg0) {
//                trackApp.getmHandler().obtainMessage(0, "添加entity回调接口消息 : " + arg0).sendToTarget();
            }

            // 查询entity列表回调接口
            @Override
            public void onQueryEntityListCallback(String message) {
                TraceLocation entityLocation = new TraceLocation();
                try {
                    JSONObject dataJson = new JSONObject(message);
                    if (dataJson.has("status") && dataJson.getInt("status") == 0
                            && dataJson.has("size") && dataJson.getInt("size") > 0) {
                        JSONArray entities = dataJson.getJSONArray("entities");
                        JSONObject entity = entities.getJSONObject(0);
                        JSONObject point = entity.getJSONObject("realtime_point");
                        JSONArray location = point.getJSONArray("location");
                        entityLocation.setLongitude(location.getDouble(0));
                        entityLocation.setLatitude(location.getDouble(1));
                    }
                } catch (JSONException e) {
//                    trackApp.getmHandler().obtainMessage(0, "解析entityList回调消息失败").sendToTarget();
                    return;
                }
//                showRealtimeTrack(entityLocation);
            }

            @Override
            public void onReceiveLocation(TraceLocation location) {
//                showRealtimeTrack(location);
            }

        };
    }

    /**
     * 开启轨迹服务
     */
    private void startTrace() {
        trackApp = (MyApplication) getApplicationContext();
        // 通过轨迹服务客户端client开启轨迹服务
        trackApp.getClient().startTrace(trackApp.getTrace(), startTraceListener);
        if (!MonitorService.isRunning) {
            // 开启监听service
            MonitorService.isCheck = true;
            MonitorService.isRunning = true;
            startMonitorService();
        }
    }

    public void startMonitorService() {
        serviceIntent = new Intent(trackApp, MonitorService.class);
        trackApp.startService(serviceIntent);
    }
}
